import { defineStore } from "pinia";
import { getStore, setStore } from "@/utils/localStorage";
import { store } from "@/store";
import { type RouteRecordRaw, type RouteLocationNormalized } from "vue-router";

type TagView = Partial<RouteLocationNormalized>;
export const useTagsViewStore = defineStore({
  id: "tagsView-store",
  state: () => ({
    // 存储标签页信息（路由信息）
    tagsViews: getStore({ name: "configure" }).cacheTagsView ? getStore({ name: "tags" }) ?? [] : []
  }),
  actions: {
    addTagView(view: TagView) {
      // 检查是否已经存在相同的 tagsViews
      const index = this.tagsViews.findIndex(
        (v: RouteRecordRaw) => v.path.includes(view.path) || v.fullPath === view.fullPath
      );
      if (index !== -1) {
        // 防止 query 参数丢失
        this.tagsViews[index].fullPath !== view.fullPath && (this.tagsViews[index] = { ...view });
      } else {
        // 添加新的 tagsViews
        this.tagsViews.push(view);
      }
      setStore({ name: "tags", content: this.tagsViews });
    },
    removeTagView(view: TagView) {
      const index = this.tagsViews.findIndex((v) => v.path === view.path);
      if (index !== -1) this.tagsViews.splice(index, 1);
    }
  }
});
export function useTagsViewStoreHook() {
  return useTagsViewStore(store);
}
